package kaiin;

import DBs.DBExec;
import DBs.Syori;

import java.net.URI;
import java.net.URISyntaxException;

import java.io.IOException;
import java.io.PrintWriter;

import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LogIn extends HttpServlet implements Syori{

	public void doGet(HttpServletRequest req, HttpServletResponse res)
	throws IOException, ServletException{
		this.doPost(req, res);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
	throws IOException, ServletException{

		req.setCharacterEncoding("utf-8");

		String sql = "select * from kokyaku";

		DBExec dbe = new DBExec();
		dbe.selectTable(sql, this, req, res);

	}

	public void syori(ResultSet rs, HttpServletRequest req, HttpServletResponse res){

		String message = "ログインできませんでした！";
		String title = "ログイン失敗";


		String id = req.getParameter("identify");
		if(id == null) id = "";
		String password = req.getParameter("pass");
		if(password == null) password ="";

		String itemID = req.getParameter("cateText");
		if(itemID == null) itemID = "";

		try{
			while(rs.next()){

				//IDが登録されているか検索
				if(id.equals(rs.getString("user_id"))){

					//パスワードを照合
					if(password.equals(rs.getString("password"))){

						KaiinBeans kbean = new KaiinBeans();

						//kbeanに値をセット
						beansSet(rs, kbean);
						//ログイン状態に設定
						kbean.setLogIn(true);

						HttpSession session = req.getSession(true);
						session.setAttribute("kaiin", kbean);

						message = "ログインしました！";
						title = "ログイン完了";

						break;
					}
				}
			}

			req.setAttribute("title", title);
			req.setAttribute("message", message);

			RequestDispatcher dp = req.getRequestDispatcher("/src/jsp/thanks.jsp");
			dp.forward(req, res);

		}catch(SQLException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}catch(ServletException e){
			e.printStackTrace();
		}

	}

	public void beansSet(ResultSet rs, KaiinBeans kbean)
	throws SQLException{

		kbean.setUser_id(rs.getString("user_id"));
		kbean.setPassword(rs.getString("password"));
		kbean.setSimei(rs.getString("simei"));
		kbean.setHurigana(rs.getString("hurigana"));
		kbean.setSeibetu(rs.getString("seibetu"));
		kbean.setYuubin(rs.getString("yuubin"));
		kbean.setJuusyo(rs.getString("juusyo"));
		kbean.setTel(rs.getString("tel"));
		kbean.setKeitai(rs.getString("keitai"));
		kbean.setMail(rs.getString("mail"));
		kbean.setSeinen(rs.getInt("seinen") + "");

	}

}
